//
//  APPServer.m
//  CYWFrame
//
//  Created by Macx on 2017/8/1.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "APPServer.h"

@implementation APPServer

+ (void)refreshToken {
    
//    NSLog(@"当前token = %@", GetUserDefaule(Token));
    
    // 传递version给后台， 后台同步设置，后台设置的版本号与这个工程当前的版本号相同，那么部分功能开启隐藏，否则开启
    
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *currentVersion = infoDic[@"CFBundleShortVersionString"];
    
    NSLog(@"version====%@", currentVersion);
    NSDictionary *param = @{@"ios_v":currentVersion};
    NSLog(@"the dict is %@", param);
    
    int currDate = [[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970];
    int expired = [[GetUserDefaule(Token) valueForKey:@"expired_at"] intValue];
    
    if (currDate > expired || GetUserDefaule(USERINFO) == NULL) {
        [[NetworkTool sharedTool] requestWithName:@"获取游客token" URLString:APITemporary parameters:param method:@"POST" callBack:^(id responseObject) {
            
            NSString *state = [NSString stringWithFormat:@"%@", responseObject[@"data"][@"sign"]];
            
            SetUserDefaule(responseObject[@"data"], Token);
            
            SetAppEnvironmentBG(state, AppEnBG);
        }];
    }
    
    else {
        [[NetworkTool sharedTool] requestWithName:@"刷新用户token" URLString:APITokenRefresh parameters:param method:@"POST" callBack:^(id responseObject) {
            
            NSString *state = [NSString stringWithFormat:@"%@", responseObject[@"data"][@"sign"]];
			
			if (!responseObject[@"data"][@"role"]) {
				SetUserDefaule(responseObject[@"data"], Token);
			}
			else {
				//如果拿到角色是空可以做相应处理，目前后续会有”请先登录“弹窗此处不做处理也行
			}
            SetAppEnvironmentBG(state, AppEnBG);
        }];
    }

}

//这个主要是第一次安装时监测用户有没点允许网络，如果还没点，则延迟请求
+ (void)checkNetworkAndRefreshToken {
	AFNetworkReachabilityManager *afNetworkReachabilityManager = [AFNetworkReachabilityManager sharedManager];
	
	//这个可以放在需要侦听的页面
	//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(afNetworkStatusChanged:) name:AFNetworkingReachabilityDidChangeNotification object:nil];
	[afNetworkReachabilityManager startMonitoring];  //开启网络监视器；
	[afNetworkReachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
		switch (status) {
			case AFNetworkReachabilityStatusNotReachable:{
				NSLog(@"网络不通：%@",@(status) );
				dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0/*延迟执行时间*/ * NSEC_PER_SEC));
				
				dispatch_after(delayTime, dispatch_get_main_queue(), ^{
					[self checkNetworkAndRefreshToken];
				});
				break;
			}
			case AFNetworkReachabilityStatusReachableViaWiFi:{
				NSLog(@"网络通过WIFI连接：%@",@(status));
				[APPServer refreshToken];
				break;
			}
			case AFNetworkReachabilityStatusReachableViaWWAN:{
				NSLog(@"网络通过无线连接：%@",@(status) );
				[APPServer refreshToken];
				break;
			}
			default:
				break;
		}
	}];
}

@end
